/**
 * Promies化
 */
function promisefy(func) {
  return function(options){
    return new Promise((resolve, reject)=>{
      func({
        ...options,
        success:res=>{
          resolve(res);
        },
        fail:e=>{
          reject(e);
        }
      })
    });
  }
}

/**
 * 会话类，可以写复杂一点，加入处理cookie的逻辑
 */
class Session {
  request = promisefy(wx.request)
}

/**进行配置 */
const config = {
  baseUrl: "https://www.lanotherl.com",
  apis:[
    {
      name:"volunteer.taskDetails"
    },
    {
      name:"task.clue"  // url:"/task/clue"
    },
    {
      name:"volunteer.findVolunteer",
      url:"/volunteer/findVolunteer/{id}"
    }
  ]
}

class Api{
  constructor(session, config){
    this.session = session;
    this.config = config;
  }
  async callApi({name="", data={}, success, fail, complete}){
    let {url, method} = this.getConfig({name});
    // 处理url中有参数的情况，例如/volunteer/findVolunteer/{id}
    url = url.replace(/{(.*)}/, function(matchStr,key){
      return data[key]||"";
    });
    let fullUrl = this.config.baseUrl + url; //完整的链接
    console.debug({url:fullUrl, method, data})
    let res = await this.session.request({url:fullUrl, method, data});
    let {code, data:_data, message, success:_success} = res.data;
    if(!success){
      // 报错？
      let e = new Error(message);
      fail&&fail(e);
      complete&&complete(e);
      throw e;
    }
    _success&&_success(_data);
    complete&&complete(_data);
    return _data;
  }
  getConfig({name}){
    for(var item of this.config.apis){
      if(item.name==name){
        if(!item.url){
          item.url = "/" + name.replace(/\./g,"/")
        }
        item.method = item.method||"GET";
        return item;
      }
    }
    return;
  }
}

/**
 * 用户类，可以监听一些请求结果，加一些状态参数，在这里进行保存
 */
export class Client{
  constructor(config){
    this.session = new Session();
    this.api = new Api(this.session, config);
  }
  callApi(options){
    return this.api.callApi(options)
  }
}

export const client = new Client(config);
global.client = client;

